<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 2016/9/28
 * Time: 23:58
 */

namespace Home\Controller;


use Common\Utils\Constants;
use Common\Utils\WeChatUtils;

use Home\Logic\UserLogic;
use Think\Controller;
use Think\Log;

class WeChatController extends Controller
{
    private $_utils;
    public function __construct()
    {
        parent::__construct();
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $this->_utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
        $this->assign('system_name',$this->getSystemName());
    }
    public function firstVaild()
    {
        //检验签名的合法性
        if ($this->_checkSignature()) {
            //签名合法，告知微信公众平台服务器
            echo $_GET['echostr'];
        }
    }
    protected function getSystemName(){
        $system_name = M('Config')->where(array('name'=>Constants::CONFIG_SYSTEM_NAME))->getField('value');
        return $system_name;
    }
    /**
     * 验证签名
     * @return bool
     */
    private function _checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'gouhuiwan';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }
    //网页授权回调
    public function html_return(){
        cookie(null);//清空
        $file = 'log';
        $code = I('code');
        $state = I('state');
        if('' != $state && strstr($state,"#")) {
            $state = explode('#',$state);
            $state = $state[0];
        }

        $result = $this->_utils->getHtmlAccessToken($code);
        if(!$result){
            return;
        }
        cookie('openid',$result->openid);//存入sessoin
        $model = D('User');
        $user = $model->where(array('openid'=>':openid'))->bind(array(':openid'=>$result->openid))->find();
        //获取用户详细信息
        $userInfo = $this->_utils->getUserInfo($result->access_token,$result->openid);
        if(!$user){
            $logic = new UserLogic();
            $info = $this->makeUser($userInfo,$user);
            $user_id = $logic->addUser($result->openid,$info['nickname'],$info['sex'],$info['head_url']);
//            if(!empty($sup_user_id)){
//                $result = $logic->bindUser($user_id,$sup_user_id);//绑定上级
//                Log::write('bindUser---:'.$result);
//            }
            $user = D('User')->where(array('id'=>$user_id))->find();
            $isNewRegister = true;
        }else{
            $user = $this->makeUser($userInfo,$user);
            $model->save($user);
            $isNewRegister = false;
        }
        if(empty($user['phone'])){
            $newUser = true;//是否完善资料
        }else{
            $newUser = false;
        }
        cookie('user',$user, 3600 * 24);//存入sessoin
//        $aaa = session('user');
//        var_dump($aaa);
//        return;
        if(!empty($state)){
            $array = explode('_',$state);
            $user_id = $array[0];
            $type = $array[1];
            if($type == 'aboutUS'){
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                $url = "$protocol$_SERVER[HTTP_HOST]".'/Home/Index/gameShow';
                header("location: ".$url);
                exit();
            }
            if($type == 'room' && !$newUser){
                $room_id = $array[2];
                $password = $array[3];
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                $url = "$protocol$_SERVER[HTTP_HOST]".'/Home/Room/detail?room_id='.$room_id.'&is_no_need_password=1';
                header("location: ".$url);
                exit();
            }
            if ($type == 'push') {
                $userLogic = new UserLogic();
                $userLogic->visitor($user_id,$user['id'],$isNewRegister);
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                $url = "$protocol$_SERVER[HTTP_HOST]" . '/Home/WeChat/push_code?user_id=' . $user_id;
                header("location: " . $url);
                exit();
            }
        }

        if($newUser){
            $this->redirect('/Home/Index/settings');
        }else {
            $this->redirect('/Home/Index/index');
        }
    }


    private function makeUser($userInfo,$user){
        $user['nickname'] =  match_chinese($userInfo->nickname);
        $user['head_url'] = $userInfo->headimgurl;
        $sex = $userInfo->sex.'';
        $user['sex'] = $sex == '2' ? 1 : 0;
        return $user;
    }


//    public function login($user_id=null,$url=null){
//        if(empty($user_id)){
//            $user_id = '0';
//        }
//        if(!empty($url)) {
//            $user_id .= '_' . $url;
//        }
//        $this->_utils->getUserCode($user_id);
//    }
    public function loginRoom(){
        $user_id = I('user_id');
        $type = I('type');
        $room_id = I('room_id');
        $password = I('password');

        $this->_utils->getUserCode($user_id.'_'.$type.'_'.$room_id.'_'.$password);
    }

    public function loginByPush(){
        $user_id = I('user_id');
        $this->_utils->getUserCode($user_id.'_push');
    }

    public function aboutUs(){
        $this->_utils->getUserCode('0_aboutUS');
    }

    public function push_code(){
        $show = $config = D('Config')->where(array('name' => Constants::CONFIG_PROMOTION_SHOW))->find();
        $code_bg = $config = D('Config')->where(array('name'=>Constants::CONFIG_PROMOTION_CODE_BG))->find();
        $show = html_entity_decode($show['value']);
        $this->jsSDK();
        $user_id = I('user_id');
        $user = cookie('user');
        $user = D('User')->where(array('id'=>$user['id']))->field('id,user_type')->find();
        //显示用户浏览量信息
//        if($user['user_type'] == Constants::USER_TYPE_AGENT){
            //显示用户浏览量信息
            $logic = new UserLogic();
            $pageviews = $logic->getUserPageViews($user['id']);
            $show_pageviews =$pageviews['show_pageviews'];
            $money =$pageviews['money'];
//        }else{
//            $show_pageviews = '';
//            $money = '';
//        }

        $this->assign('show_pageviews', $show_pageviews);
        $this->assign('money', $money);

        $is_current_user = $user_id == $user['id'] ? 1 : 0;

        $this->assign('context', $show);
        $this->assign('code_bg', $code_bg['value']);
        $this->assign('user_id',$user_id);
        $this->assign('is_current_user',$is_current_user);
        $this->display('Me/pushCode');
    }

    /**
     * ajax 获取用户二维码
     */
    public function qrCode(){
        $user_id = I('user_id');
//        var_dump($user);
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
        $utils->getQRCode($user_id);
    }

    protected function jsSDK(){
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
        $ticket = $utils->getJsApiTicket();
        $noncestr = $utils->getRandCode();//获取随机码
        $timestamp = time();//时间戳
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
//        $url = U('Home/WeChat/invite/'.$user['id']);
        $str = 'jsapi_ticket=' . $ticket . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url='.$url;
        $signature = sha1($str);
        $this->assign('host',"$protocol$_SERVER[HTTP_HOST]");
        $this->assign('appId',$APPID);
        $this->assign('ticket',$ticket);
        $this->assign('noncestr',$noncestr);
        $this->assign('timestamp',$timestamp);
        $this->assign('signature',$signature);
        $this->assign('BASE_URL',C('BASE_URL'));//域名
    }

}